/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2024/6/12
 * Time: 11:33
 */

#include "CardDeck.h"

#include "Card.h"
namespace Upgrade {
    CardDeck::CardDeck(int _num, int _bottomNum)
        : nums_(_num)
        , bottom_card_nums_(_bottomNum)
    {
        InitDeck();
    }

    // 洗牌
    void CardDeck::Shuffle()
    {
        // Fisher-Yates 洗牌算法
        std::random_device    rd;// 非确定性随机数生成器
        default_random_engine e(rd());
        for(int i = all_cards_.size() - 1; i > 0; --i) {
            uniform_int_distribution<int> dist(0, i);
            int                           j = dist(e);
            swap(all_cards_[i], all_cards_[j]);
        }
    }

    void CardDeck::Print()
    {
        for(auto card : all_cards_)
            card->Print();
    }

    CardSPtr CardDeck::Deal()
    {
        CardSPtr ret = nullptr;
        if(all_cards_.size() > haveBottomCard_) {
            ret = all_cards_.back();
            all_cards_.pop_back();
        }
        return ret;
    }

    void CardDeck::SetBottomCard(int _num)
    {
        bottom_card_nums_ = _num;
        haveBottomCard_ = bottom_card_nums_ != 0;
    }

    void CardDeck::InitDeck()
    {
        // 添加nums_副牌
        for(int i = 0; i < nums_; ++i) {
            // 添加普通牌
            auto mate = QMetaEnum::fromType<CardSuit>();
            for(int j = 1; j < mate.keyCount() - 1; ++j) {
                auto suit = static_cast<CardSuit>(mate.value(j));
                for(int rank = static_cast<int>(CardRank::Two); rank <= static_cast<int>(CardRank::Ace); ++rank) {
                    QColor color = (suit == CardSuit::HeartsSuit || suit == CardSuit::DiamondsSuit) ? Qt::red : Qt::black;
                    all_cards_.emplace_back(make_shared<Card>(static_cast<CardRank>(rank), color, suit));
                }
            }

            // 添加大小王
            all_cards_.emplace_back(make_shared<Card>(CardRank::SmallJoker, Qt::black, CardSuit::JokerSuit));
            all_cards_.emplace_back(make_shared<Card>(CardRank::BigJoker, Qt::red, CardSuit::JokerSuit));
        }
    };
} // Upgrade